import { defineStore } from "pinia";
import { ref } from "vue";
import { useLogStore } from "./logStore";
import { WeChatApiService } from "../services/apiService";

export const useTransferStore = defineStore("transfer", () => {
  const logStore = useLogStore();

  // 状态
  const port = ref(8989);
  const friends = ref([]);
  const groups = ref([]);
  const groupMembers = ref({});
  const publicAccounts = ref([]);
  const rules = ref([]);

  // 加载状态
  const loading = ref({
    friends: false,
    groups: false,
    members: false,
    publicAccounts: false,
  });

  // 创建API服务实例
  let apiService = new WeChatApiService(port.value);

  /**
   * 设置端口号
   * @param {number} newPort - 新的端口号
   */
  function setPort(newPort) {
    port.value = newPort;
    // 为新端口创建新的API服务实例
    apiService = new WeChatApiService(newPort);
    logStore.addMessage(`转发规则管理器: 端口已更新为 ${newPort}`);
  }

  // Getters
  /**
   * 获取所有可用的转发源
   */
  const allSources = () => {
    const sources = [];

    // 添加好友
    friends.value.forEach((friend) => {
      sources.push({
        id: friend.wxid,
        name: friend.nickname || friend.wxid,
        type: "friend",
        avatar: friend.avatar,
      });
    });

    // 添加群组
    groups.value.forEach((group) => {
      sources.push({
        id: group.wxid,
        name: group.nickname || group.wxid,
        type: "group",
        avatar: group.avatar,
      });

      // 添加群成员
      const members = groupMembers.value[group.wxid] || [];
      members.forEach((member) => {
        sources.push({
          id: member.wxid,
          name: `${group.nickname || group.wxid} - ${
            member.nickname || member.wxid
          }`,
          type: "group_member",
          groupId: group.wxid,
          avatar: member.avatar,
        });
      });
    });

    return sources;
  };

  /**
   * 获取所有可用的转发目标
   */
  const allTargets = () => {
    const targets = [];

    // 添加好友
    friends.value.forEach((friend) => {
      targets.push({
        id: friend.wxid,
        name: friend.nickname || friend.wxid,
        type: "friend",
        avatar: friend.avatar,
      });
    });

    // 添加群组
    groups.value.forEach((group) => {
      targets.push({
        id: group.wxid,
        name: group.nickname || group.wxid,
        type: "group",
        avatar: group.avatar,
      });
    });

    return targets;
  };

  // Actions
  /**
   * 加载好友列表
   * @param {number} currentPort - 当前端口号
   */
  async function loadFriends(currentPort = port.value) {
    if (currentPort !== port.value) {
      setPort(currentPort);
    }

    loading.value.friends = true;

    try {
      logStore.addMessage("正在获取好友列表...");

      const result = await apiService.getFriendList();

      if (result.errno === 0 && result.data) {
        friends.value = result.data;
        logStore.addMessage(`成功获取 ${friends.value.length} 个好友`);
        return friends.value;
      } else {
        throw new Error(result.errmsg || "获取好友列表失败");
      }
    } catch (error) {
      logStore.addMessage(`获取好友列表失败: ${error.message}`);
      throw error;
    } finally {
      loading.value.friends = false;
    }
  }

  /**
   * 加载群组列表
   * @param {number} currentPort - 当前端口号
   */
  async function loadGroups(currentPort = port.value) {
    if (currentPort !== port.value) {
      setPort(currentPort);
    }

    loading.value.groups = true;

    try {
      logStore.addMessage("正在获取群组列表...");

      const result = await apiService.getGroupList();

      if (result.errno === 0 && result.data) {
        groups.value = result.data;
        logStore.addMessage(`成功获取 ${groups.value.length} 个群组`);
        return groups.value;
      } else {
        throw new Error(result.errmsg || "获取群组列表失败");
      }
    } catch (error) {
      logStore.addMessage(`获取群组列表失败: ${error.message}`);
      throw error;
    } finally {
      loading.value.groups = false;
    }
  }

  /**
   * 加载群成员列表
   * @param {string} groupId - 群组ID
   * @param {number} currentPort - 当前端口号
   */
  async function loadGroupMembers(groupId, currentPort = port.value) {
    if (currentPort !== port.value) {
      setPort(currentPort);
    }

    loading.value.members = true;

    try {
      logStore.addMessage(`正在获取群 ${groupId} 的成员列表...`);

      const result = await apiService.getGroupMembers(groupId);

      if (result.errno === 0 && result.data) {
        // 更新特定群的成员
        groupMembers.value = {
          ...groupMembers.value,
          [groupId]: result.data,
        };

        logStore.addMessage(
          `成功获取群 ${groupId} 的 ${result.data.length} 个成员`
        );
        return result.data;
      } else {
        throw new Error(result.errmsg || "获取群成员列表失败");
      }
    } catch (error) {
      logStore.addMessage(`获取群成员列表失败: ${error.message}`);
      throw error;
    } finally {
      loading.value.members = false;
    }
  }

  /**
   * 加载公众号列表
   * @param {number} currentPort - 当前端口号
   */
  async function loadPublicAccounts(currentPort = port.value) {
    if (currentPort !== port.value) {
      setPort(currentPort);
    }

    loading.value.publicAccounts = true;

    try {
      logStore.addMessage("正在获取公众号列表...");

      const result = await apiService.getPublicAccountList();

      if (result.errno === 0 && result.data) {
        publicAccounts.value = result.data;
        logStore.addMessage(`成功获取 ${publicAccounts.value.length} 个公众号`);
        return publicAccounts.value;
      } else {
        throw new Error(result.errmsg || "获取公众号列表失败");
      }
    } catch (error) {
      logStore.addMessage(`获取公众号列表失败: ${error.message}`);
      // 这个错误不是致命的，所以我们只记录而不抛出
      return [];
    } finally {
      loading.value.publicAccounts = false;
    }
  }

  /**
   * 加载所有数据
   * @param {number} currentPort - 当前端口号
   */
  async function loadAllData(currentPort = port.value) {
    if (currentPort !== port.value) {
      setPort(currentPort);
    }

    logStore.addMessage("正在加载所有联系人数据...");

    try {
      await Promise.all([
        loadFriends(currentPort),
        loadGroups(currentPort),
        loadPublicAccounts(currentPort),
      ]);

      logStore.addMessage("所有联系人数据加载完成");

      // 加载规则
      loadRulesFromLocalStorage();

      return {
        friends: friends.value,
        groups: groups.value,
        publicAccounts: publicAccounts.value,
      };
    } catch (error) {
      logStore.addMessage(`加载联系人数据失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 添加转发规则
   * @param {Object} rule - 转发规则
   */
  function addRule(rule) {
    // 生成唯一ID
    const id =
      Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
    const newRule = {
      id,
      ...rule,
      port: port.value,
      enabled: true,
      createdAt: new Date().toISOString(),
    };

    rules.value.push(newRule);
    saveRulesToLocalStorage();
    logStore.addMessage(`已添加新的转发规则: ${rule.name || id}`);
    return newRule;
  }

  /**
   * 更新转发规则
   * @param {string} id - 规则ID
   * @param {Object} updatedRule - 更新后的规则
   */
  function updateRule(id, updatedRule) {
    const index = rules.value.findIndex((rule) => rule.id === id);
    if (index !== -1) {
      rules.value[index] = {
        ...rules.value[index],
        ...updatedRule,
        updatedAt: new Date().toISOString(),
      };

      saveRulesToLocalStorage();
      logStore.addMessage(`已更新转发规则: ${updatedRule.name || id}`);
      return rules.value[index];
    }

    logStore.addMessage(`更新转发规则失败: 未找到ID为 ${id} 的规则`);
    return null;
  }

  /**
   * 删除转发规则
   * @param {string} id - 规则ID
   */
  function deleteRule(id) {
    const index = rules.value.findIndex((rule) => rule.id === id);
    if (index !== -1) {
      const deletedRule = rules.value.splice(index, 1)[0];
      saveRulesToLocalStorage();
      logStore.addMessage(`已删除转发规则: ${deletedRule.name || id}`);
      return true;
    }

    logStore.addMessage(`删除转发规则失败: 未找到ID为 ${id} 的规则`);
    return false;
  }

  /**
   * 获取指定端口的规则
   * @param {number} portNumber - 端口号
   */
  function getRulesByPort(portNumber) {
    return rules.value.filter((rule) => rule.port === portNumber);
  }

  /**
   * 切换规则启用状态
   * @param {string} id - 规则ID
   */
  function toggleRuleEnabled(id) {
    const index = rules.value.findIndex((rule) => rule.id === id);
    if (index !== -1) {
      rules.value[index].enabled = !rules.value[index].enabled;
      saveRulesToLocalStorage();

      const status = rules.value[index].enabled ? "启用" : "禁用";
      logStore.addMessage(
        `已${status}转发规则: ${rules.value[index].name || id}`
      );

      return rules.value[index];
    }

    logStore.addMessage(`切换规则状态失败: 未找到ID为 ${id} 的规则`);
    return null;
  }

  /**
   * 保存规则到本地存储
   */
  function saveRulesToLocalStorage() {
    try {
      localStorage.setItem("wx_transfer_rules", JSON.stringify(rules.value));
    } catch (error) {
      logStore.addMessage(`保存转发规则到本地存储失败: ${error.message}`);
    }
  }

  /**
   * 从本地存储加载规则
   */
  function loadRulesFromLocalStorage() {
    try {
      const savedRules = localStorage.getItem("wx_transfer_rules");
      if (savedRules) {
        rules.value = JSON.parse(savedRules);
        logStore.addMessage(
          `已从本地存储加载 ${rules.value.length} 条转发规则`
        );
      } else {
        rules.value = [];
      }
    } catch (error) {
      logStore.addMessage(`从本地存储加载转发规则失败: ${error.message}`);
      rules.value = [];
    }
  }

  /**
   * 初始化
   */
  function initialize() {
    loadRulesFromLocalStorage();
  }

  // 初始化
  initialize();

  return {
    // 状态
    port,
    friends,
    groups,
    groupMembers,
    publicAccounts,
    rules,
    loading,

    // Getters
    allSources,
    allTargets,

    // Actions
    setPort,
    loadFriends,
    loadGroups,
    loadGroupMembers,
    loadPublicAccounts,
    loadAllData,
    addRule,
    updateRule,
    deleteRule,
    getRulesByPort,
    toggleRuleEnabled,
    saveRulesToLocalStorage,
    loadRulesFromLocalStorage,
  };
});
